'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Container,
  Box,
  Typography,
  Paper,
  CircularProgress,
  Alert,
  Button,
  Card,
  CardContent,
  CardActions,
  Grid,
  Chip,
  IconButton,
  useTheme,
  alpha,
  Fade,
} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import WorkIcon from '@mui/icons-material/Work';
import VisibilityIcon from '@mui/icons-material/Visibility';
import EmailIcon from '@mui/icons-material/Email';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import AttachMoneyIcon from '@mui/icons-material/AttachMoney';
import PeopleIcon from '@mui/icons-material/People';
import MarkEmailReadIcon from '@mui/icons-material/MarkEmailRead';
import Navbar from '@/components/Navbar';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

interface JobPost {
  id: number;
  title: string;
  company_name: string;
  location: string;
  salary_min?: number;
  salary_max?: number;
  salary_range?: string; // 添加salary_range字段
  job_type: string;
  is_active: boolean;
  views: number;
  applications: number;
  created_at: string;
  description?: string;
  requirements?: string;
}

interface JobPostStats {
  total_resumes: number;
  read_resumes: number;
  unread_resumes: number;
}

export default function JobPostsPage() {
  const router = useRouter();
  const theme = useTheme();
  const [jobPosts, setJobPosts] = useState<JobPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [fadeIn, setFadeIn] = useState(false);

  const fetchJobPosts = async () => {
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/login');
        return;
      }

      const headers = {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      };

      const response = await fetch('/api/profile/job-posts', { headers });

      if (response.status === 401) {
        // 清除无效的token和用户数据，然后跳转到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        localStorage.removeItem('userData');
        router.push('/login');
        return;
      }

      if (!response.ok) {
        throw new Error('获取招聘公告失败');
      }

      const data = await response.json();
      setJobPosts(data);
      setFadeIn(true);
    } catch (error) {
      console.error('获取招聘公告失败:', error);
      setError((error as Error).message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 立即检查登录状态
    const token = localStorage.getItem('token');
    if (!token) {
      console.log('用户未登录，跳转到登录页面');
      router.push('/login');
      return;
    }

    fetchJobPosts();
  }, [router]);

  const handleJobPostClick = (jobPostId: number) => {
    router.push(`/profile/job-posts/${jobPostId}`);
  };

  const formatSalary = (min?: number, max?: number, salaryRange?: string) => {
    // 优先使用salary_range字段
    if (salaryRange) {
      return salaryRange;
    }
    // 兼容旧的格式
    if (!min && !max) return '面议';
    if (min && max) return `${min}k-${max}k`;
    if (min) return `${min}k+`;
    return '面议';
  };

  const getJobTypeColor = (jobType: string) => {
    switch (jobType) {
      case 'full_time':
      case 'full-time':
        return 'primary';
      case 'part_time':
      case 'part-time':
        return 'secondary';
      case 'internship':
        return 'info';
      case 'contract':
        return 'warning';
      default:
        return 'default';
    }
  };

  const getJobTypeLabel = (jobType: string) => {
    switch (jobType) {
      case 'full_time':
      case 'full-time':
        return '全职';
      case 'part_time':
      case 'part-time':
        return '兼职';
      case 'internship':
        return '实习';
      case 'contract':
        return '合同工';
      default:
        return jobType;
    }
  };

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  if (error) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Alert severity="error" sx={{ mt: 4 }}>
          {error}
          <Button 
            onClick={() => window.location.reload()} 
            sx={{ ml: 2 }} 
            size="small"
          >
            重新加载
          </Button>
        </Alert>
      </Container>
    );
  }

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: 'background.default' }}>
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Fade in={fadeIn} timeout={800}>
          <Box>
            {/* 页面头部 */}
            <Paper
              elevation={0}
              sx={{
                p: 3,
                mb: 4,
                borderRadius: '16px',
                backgroundColor: alpha('#fff', 0.9),
                backdropFilter: 'blur(10px)',
                boxShadow: '0 4px 30px rgba(0, 0, 0, 0.05)',
                border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
              }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                <IconButton 
                  onClick={() => router.back()}
                  sx={{ mr: 2 }}
                >
                  <ArrowBackIcon />
                </IconButton>
                <WorkIcon sx={{ mr: 2, color: theme.palette.primary.main }} />
                <Typography variant="h4" sx={{ fontWeight: 600 }}>
                  我的招聘公告
                </Typography>
              </Box>
              <Typography variant="body1" color="text.secondary">
                管理您发布的招聘公告，查看简历投递情况
              </Typography>
            </Paper>

            {/* 招聘公告列表 */}
            {jobPosts.length > 0 ? (
              <Grid container spacing={3}>
                {jobPosts.map((jobPost) => (
                  <Grid item xs={12} md={6} lg={4} key={jobPost.id}>
                    <Card
                      sx={{
                        height: '100%',
                        cursor: 'pointer',
                        transition: 'all 0.3s ease',
                        '&:hover': {
                          transform: 'translateY(-4px)',
                          boxShadow: '0 8px 25px rgba(0,0,0,0.1)',
                        },
                      }}
                      onClick={() => handleJobPostClick(jobPost.id)}
                    >
                      <CardContent>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
                          <Typography variant="h6" sx={{ fontWeight: 600, flex: 1 }}>
                            {jobPost.title}
                          </Typography>
                          <Chip
                            label={jobPost.is_active ? '招聘中' : '已暂停'}
                            color={jobPost.is_active ? 'success' : 'default'}
                            size="small"
                          />
                        </Box>

                        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                          {jobPost.company_name}
                        </Typography>

                        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 2 }}>
                          <Chip
                            icon={<LocationOnIcon fontSize="small" />}
                            label={jobPost.location || '未指定'}
                            size="small"
                            variant="outlined"
                          />
                          <Chip
                            icon={<AttachMoneyIcon fontSize="small" />}
                            label={formatSalary(jobPost.salary_min, jobPost.salary_max, jobPost.salary_range)}
                            size="small"
                            variant="outlined"
                          />
                          <Chip
                            label={getJobTypeLabel(jobPost.job_type)}
                            size="small"
                            color={getJobTypeColor(jobPost.job_type) as any}
                            variant="outlined"
                          />
                        </Box>

                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 2 }}>
                          <Box sx={{ display: 'flex', gap: 2 }}>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                              <VisibilityIcon fontSize="small" color="action" />
                              <Typography variant="caption" color="text.secondary">
                                {jobPost.views || 0}
                              </Typography>
                            </Box>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                              <PeopleIcon fontSize="small" color="action" />
                              <Typography variant="caption" color="text.secondary">
                                {jobPost.applications || 0}
                              </Typography>
                            </Box>
                          </Box>
                          <Typography variant="caption" color="text.secondary">
                            {format(new Date(jobPost.created_at), 'MM/dd', { locale: zhCN })}
                          </Typography>
                        </Box>
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            ) : (
              <Paper
                sx={{
                  p: 6,
                  textAlign: 'center',
                  borderRadius: '16px',
                }}
              >
                <WorkIcon sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
                <Typography variant="h6" color="text.secondary" sx={{ mb: 2 }}>
                  暂无招聘公告
                </Typography>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
                  您还没有发布任何招聘公告
                </Typography>
                <Button variant="contained" color="primary">
                  发布招聘公告
                </Button>
              </Paper>
            )}
          </Box>
        </Fade>
      </Container>
    </Box>
  );
} 